package cn.usian.jyzx.user.service.impl;


import cn.usian.comon.exception.JyzxException;
import cn.usian.jyzx.model.constant.Constant;
import cn.usian.jyzx.model.dto.h5.UserLoginDto;
import cn.usian.jyzx.model.dto.h5.UserRegisterDto;
import cn.usian.jyzx.model.entity.user.UserAddress;
import cn.usian.jyzx.model.entity.user.UserInfo;
import cn.usian.jyzx.model.vo.common.ResultCodeEnum;
import cn.usian.jyzx.model.vo.h5.UserInfoVo;
import cn.usian.jyzx.user.mapper.UserMapper;
import cn.usian.jyzx.user.service.UserService;
import cn.usian.utils.HttpUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
//验证码
    @Override
    public void sendCode(String phone) {
        String host = "https://jmsms.market.alicloudapi.com";
        String path = "/sms/send";
        String method = "POST";
        String appcode = "93fb500afac64316a2c1c32ce2622fbf";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        String s = RandomStringUtils.randomNumeric(4);
        Map<String, String> querys = new HashMap<String, String>();

        querys.put("mobile", phone);
        querys.put("templateId", "JM1000372");
        querys.put("value", s);
        Map<String, String> bodys = new HashMap<String, String>();


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        redisTemplate.opsForValue().set(Constant.CODE,s,5,TimeUnit.MINUTES);
    }
// 注册
    @Override
    public void register(UserRegisterDto userRegisterDto) {
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userRegisterDto,userInfo);
        String code = userRegisterDto.getCode();
        String rediscode =  redisTemplate.opsForValue().get(Constant.CODE);
//        验证码错误
        if (!code.equals(rediscode)){
            throw new JyzxException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
//        密码md5加密
        String password = userRegisterDto.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        userInfo.setPassword(password);
        userInfo.setSex(1);
        userInfo.setAvatar("https://img0.baidu.com/it/u=3628503530,464378779&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1712854800&t=4ec49b1b2fb7162b202f18b54753be43");
        userInfo.setPhone(userRegisterDto.getUsername());
        userMapper.register(userInfo);
    }

    @Override
    public String login(UserLoginDto userLoginDto) {
        String password = userLoginDto.getPassword();
//       将用户输入的密码md5加密
         password = DigestUtils.md5DigestAsHex(password.getBytes());
        userLoginDto.setPassword(password);
        UserInfo userInfo = userMapper.login(userLoginDto);
//        判断用户名密码是否存在
        if (userInfo==null){
            throw new JyzxException(ResultCodeEnum.LOGIN_ERROR);
        }
        String token = UUID.randomUUID().toString();
//        存入redis一份
        redisTemplate.opsForValue().set(token,JSON.toJSONString(userInfo));
        return token;
    }

    @Override
    public UserInfoVo getCurrentUserInfo(String token) {
        String userinfojson = redisTemplate.opsForValue().get(token);
        UserInfo userinfo = JSON.parseObject(userinfojson, UserInfo.class);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userinfo,userInfoVo);
        return userInfoVo;
    }
    @Override
    public List<UserAddress> findUserAddressList(String token) {
        String userinfojson = redisTemplate.opsForValue().get(token);
        UserInfo userInfo = JSON.parseObject(userinfojson, UserInfo.class);
        Long userid = userInfo.getId();
        return  userMapper.findUserAddressList(userid);
    }


}
